/*
Copyright SecureKey Technologies Inc. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/

package config

import (
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/util/pathvar"
	"github.com/pkg/errors"
	"github.com/spf13/viper"
)

type defConfigBackend struct {
	configViper *viper.Viper
	opts        options
}

func (c *defConfigBackend) Lookup(key string) (interface{}, bool) {
	value := c.configViper.Get(key)
	if value == nil {
		return nil, false
	}
	return value, true
}

func (c *defConfigBackend) loadTemplateConfig() error {
	templatePath := c.opts.templatePath
	if templatePath == "" {
		return nil
	}

	c.configViper.AddConfigPath(pathvar.Subst(templatePath))
	err := c.configViper.ReadInConfig()
	if err != nil { // Handle errors reading the config file
		return errors.Wrapf(err, "loading config from template failed: %s", templatePath)
	}
	return nil
}
